import type { TTRoomDetailType } from '@/api/tt'
import type { TTController } from '@/controller/TT/definition'
import { getRoomValve, getTTBlErrStrKey, TT_SETTING_BlErrCode, TT_SETTING_BlErrStr } from './SmartAssistantTool'
import { BL_Err, Room_Err, type TTErrType } from './TTErrorCode'

export type RoomListType = {
  errCode_key: string
  key: string
  name: string
  roomName: string
  tempDec: number
  tempInt: number
  value: [] | TTRomeValueType[]
  valveState: number
}

export type TTRoomValueType = {
  key: string
  name: string
  value: TTRomeValueType[]
}
export type TTRomeValueType = {
  default: string
  description: string
  key: string
  max: string
  min: string
  name: string
  param: string
  step: string
  type: string
  unit: string
  value: string
}
export type AllErrListType = {
  errCode: string
  errTitle: string
  serviceRemind: string
  seveie: number
  type: string
  userRemind: string
}

type RefValue<T> = Ref<T> | ComputedRef<T>
export function useTTErrorCode(
  settings: Ref<TTRoomDetailType[]>,
  options: { isMR120: RefValue<boolean>; isMR100IRFEMS: RefValue<boolean>; roomId?: Ref<string> },
  control?: TTController.Control
) {
  const { isMR120, isMR100IRFEMS } = options
  const allErrList = ref<AllErrListType[]>([])
  const boilerErr = ref(false)
  const roomList = ref<RoomListType[]>([])

  /**
   * 获取房间列表数据
   */
  watch(
    () => settings.value,
    (settings) => {
      if (!settings || settings.length === 0) return []
      if (!options.roomId?.value && Number(options.roomId?.value) !== 0) {
        settings.forEach((item) => {
          if (['BSH.Common.Setting.Err', TT_SETTING_BlErrCode].includes(item.key)) {
            if (Number(item.value) != 0) {
              addBlErr(BL_Err, item.value as string, 'Bl_ErrCode')
            } else {
              delErr('Bl_ErrCode')
            }
          }
          if ([TT_SETTING_BlErrStr].includes(item.key)) {
            if (Number(item.value) != 0) {
              addBlErr(BL_Err, item.value as string, 'Bl_ErrStr')
            } else {
              delErr('Bl_ErrStr')
            }
          }
        })
      }

      let roomSetting = settings.find((setting) => setting.key === 'room')?.value as unknown as TTRoomValueType[]

      if (!roomSetting || roomSetting.length === 0) return
      let cleanRoomList: RoomListType[] = []

      // 当前房间 过滤其他房间setting
      if (options.roomId?.value) {
        roomSetting = roomSetting.filter((setting) => setting.key === `Rm${options.roomId?.value}`)
      }

      for (let j = 0; j < roomSetting.length; j++) {
        let roomDetail = roomSetting[j]
        let newRoomDetail: RoomListType = {
          errCode_key: '',
          key: roomDetail.key,
          name: roomDetail.name,
          roomName: '',
          tempDec: 0,
          tempInt: 0,
          value: roomDetail.value,
          valveState: 0,
        }
        let isExist = true
        for (let k = 0; k < roomDetail.value.length; k++) {
          if (
            roomDetail.value[k].key == 'Temp' ||
            (
              (roomDetail.value[k].key != undefined &&
                roomDetail.value[k].key.match(/SmartAssistant.TT.Setting.Rm[0-9]{1,2}Temp/)) ||
              {}
            ).input
          ) {
            let newValue = Math.abs(Number(roomDetail.value[k].value))
            newRoomDetail.tempInt = (
              Number(roomDetail.value[k].value) < 0 ? '-' + parseInt(newValue / 10 + '') : parseInt(newValue / 10 + '')
            ) as number
            newRoomDetail.tempDec =
              Number(roomDetail.value[k].value) < 0
                ? (-1 * Number(roomDetail.value[k].value)) % 10
                : Number(roomDetail.value[k].value) % 10
          } else if (
            roomDetail.value[k].key == 'Valve' ||
            roomDetail.value[k].key == 'SmartAssistant.TT.Setting.Rm' + j + 'Valve'
          ) {
            newRoomDetail.valveState = Number(roomDetail.value[k].value)
          } else if (/SmartAssistant.TT.Setting.Rm[0-9]{1,2}State/.test(roomDetail.value[k].key)) {
            newRoomDetail.valveState = Number(getRoomValve(roomDetail.value[k].value))
          } else if (
            roomDetail.value[k].key == 'ErrCode' ||
            /SmartAssistant.TT.Setting.Rm[0-9]{1,2}ErrCode/.test(roomDetail.value[k].key)
          ) {
            if (Number(roomDetail.value[k].value) !== 0) {
              let errcode = addRoomErrReturnCode(Room_Err, roomDetail.value[k].value, roomDetail.value[k].param)
              newRoomDetail.errCode_key = errcode
              if (errcode == 'P01') {
                isExist = false
              } else if (errcode == 'C01') {
                boilerErr.value = true
              }
            } else {
              newRoomDetail.errCode_key = '0'
              delErr(roomDetail.value[k].param)
            }
          }
          newRoomDetail.roomName = roomDetail.name ? roomDetail.name : '房间' + roomDetail.key.slice(2)
        }
        if (isExist) {
          cleanRoomList.push(newRoomDetail)
        }
      }
      showErr()
      roomList.value = cleanRoomList
    }
  )

  /**
   * 添加房间错误
   * @param errList
   * @param errValue
   * @param type
   * @returns
   */
  function addRoomErrReturnCode(errList: Record<string, TTErrType>, errValue: string, type: string) {
    let errDetail = getErrDetail(errList, errValue, type)
    let hasType = false
    for (let i = 0; i < allErrList.value.length; i++) {
      if (allErrList.value[i].type == type) {
        hasType = true
        allErrList.value.splice(i, 1, errDetail)
      }
    }
    if (hasType == true) {
      return errDetail.errCode
    }
    // TT详情页显示第一个房间错误，其余房间显示各自房间错误
    if (type == `Rm${options.roomId?.value || 0}_ErrCode`) {
      if (
        allErrList.value.length > 0 &&
        (allErrList.value[0].type == 'Bl_ErrCode' || allErrList.value[0].type == 'Bl_ErrStr')
      ) {
        allErrList.value.splice(1, 0, errDetail)
      } else {
        if (errDetail.errCode != 'P01') {
          allErrList.value.unshift(errDetail)
        }
      }
    } else {
      if (errDetail.errCode != 'P01') {
        allErrList.value.push(errDetail)
      }
    }
    return errDetail.errCode
  }

  /**
   * 获取错误
   * @param errList
   * @param errValue
   * @param type
   * @returns
   */
  function getErrDetail(errList: Record<string, TTErrType>, errValue: string, type: string) {
    let curErrObj: TTErrType = {
      code: '',
      key: '',
      description: '',
      user_remind: '',
      service_remind: '',
      seveie: 0,
    }
    let isHaveErr = false
    let errKey = ''
    if (type == 'Bl_ErrStr' && (isMR120.value || isMR100IRFEMS.value)) {
      errKey = getTTBlErrStrKey(errValue).toUpperCase()
      Object.values(errList).map((item) => {
        if (item.key === errKey) {
          isHaveErr = true
          curErrObj = item
        }
      })
    } else {
      if (errValue in errList) {
        isHaveErr = true
        curErrObj = errList[Number(errValue)]
      }
    }
    if (!isHaveErr) {
      curErrObj = {
        code: 'xxx',
        key: isMR120.value || isMR100IRFEMS.value ? errKey : 'xxx',
        description: '未知故障',
        user_remind: '2',
        service_remind: '▶请查阅壁挂炉说明书或者联系售后服务',
        seveie: 0,
      }
    }
    let userRemind = ''
    if (curErrObj.user_remind == '0') {
      userRemind = '此故障暂不影响设备采暖，请联系客服获得解决方案'
    } else if (curErrObj.user_remind == '1') {
      userRemind = '此故障影响设备供暖，请立即报修'
    } else if (curErrObj.user_remind == '2') {
      userRemind = '此故障暂不影响设备采暖，请联系客服获得解决方案'
    } else if (curErrObj.user_remind == '3') {
      userRemind = '将设备水压补水到0.15MPa左右，如故障仍存在请报修'
    } else if (curErrObj.user_remind == '4') {
      userRemind = '检查冷凝水排水管是否堵塞，如不能排除报修'
    } else if (curErrObj.user_remind == '5') {
      userRemind = '尝试手动复位壁挂炉，如不能排除报修'
    }
    let errDetail = {
      errTitle: curErrObj.description,
      errCode: curErrObj.key,
      userRemind,
      serviceRemind: curErrObj.service_remind,
      seveie: curErrObj.seveie,
      type,
    }
    return errDetail
  }

  /**
   * 新增锅炉错误
   */
  function addBlErr(errList: Record<string, TTErrType>, errValue: string, type: string) {
    if ((isMR100IRFEMS.value || isMR120.value) && type == 'Bl_ErrCode') {
      return
    }
    if (!isMR100IRFEMS.value && !isMR120.value && type == 'Bl_ErrStr') {
      return
    }
    let errDetail = getErrDetail(errList, errValue, type)
    let hasType = false
    for (let i = 0; i < allErrList.value.length; i++) {
      if (allErrList.value[i].type == type) {
        hasType = true
        allErrList.value.splice(i, 1, errDetail)
      }
    }
    if (hasType) {
      return
    }
    allErrList.value.unshift(errDetail)
  }

  /**
   * 删除错误
   */
  function delErr(type: string) {
    for (let i = 0; i < allErrList.value.length; i++) {
      if (allErrList.value[i].type == type) {
        allErrList.value.splice(i, 1)
      }
    }
  }

  /**
   * 显示错误
   */
  const errCodeC01 = ref(false)
  const hasCriticalErr = ref(false)
  const hasLightErr = ref(false)
  const showLightErr = ref(false)
  const errTitle = ref('')
  const errCode = ref('')
  const userRemind = ref('')
  const serviceRemind = ref('')
  function showErr() {
    console.error('showErr', allErrList.value)
    const filteredErrorList = !options.roomId
      ? allErrList.value
      : allErrList.value.filter((err) => err.type === `Rm${options.roomId?.value}_ErrCode`)
    let newErrCodeC01 = false
    if (filteredErrorList.length > 0) {
      newErrCodeC01 = filteredErrorList.some((item) => item.errCode == 'C01')
      for (let i = 0; i < filteredErrorList.length; i++) {
        let errDetail = filteredErrorList[i]
        // control.store.addNotice(errDetail)
        if (errDetail.seveie == 1) {
          errTitle.value = errDetail.errTitle
          errCode.value = errDetail.errCode
          userRemind.value = errDetail.userRemind
          serviceRemind.value = errDetail.serviceRemind
          hasCriticalErr.value = true
          hasLightErr.value = false
          showLightErr.value = false
        } else {
          errTitle.value = errDetail.errTitle
          errCode.value = errDetail.errCode
          userRemind.value = errDetail.userRemind
          serviceRemind.value = errDetail.serviceRemind
          hasCriticalErr.value = false
          hasLightErr.value = true
          showLightErr.value = false
        }
        break
      }
    } else {
      hasCriticalErr.value = false
      hasLightErr.value = false
      showLightErr.value = false
    }
    errCodeC01.value = newErrCodeC01
  }
  return {
    roomList,
    boilerErr,
    showErr,
    errCodeC01,
    hasCriticalErr,
    hasLightErr,
    showLightErr,
    errTitle,
    errCode,
    userRemind,
    serviceRemind,
    addBlErr,
    delErr,
    getErrDetail,
    addRoomErrReturnCode,
  }
}
